package com.szz.cardecision.service;

import com.szz.cardecision.entity.Consultation;
import com.szz.cardecision.entity.User;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

@Component
public class ZhipuLLMProvider implements LLMProvider {
    private final HttpClient httpClient = HttpClient.newHttpClient();

    @Override
    public String name() { return "Zhipu GLM"; }

    @Override
    public String generateAdvice(User user, Consultation c) {
        String apiKey = System.getenv("ZHIPU_API_KEY");
        String prompt = buildPrompt(user, c);
        if (apiKey == null || apiKey.isBlank()) {
            return "[Zhipu] 未配置 API Key，返回演示建议：\n" + demoAdvice(prompt);
        }

        try {
            // Example Zhipu API (adjust model/endpoint per latest docs)
            String body = "{\"model\":\"glm-4-flash\",\"input\":{\"prompt\":\"" +
                    prompt.replace("\"", "\\\"") + "\"}}";

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://open.bigmodel.cn/api/paas/v4/chat/completions"))
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
                    .build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() >= 200 && response.statusCode() < 300) {
                return "[Zhipu] " + Optional.ofNullable(response.body()).orElse("(empty)");
            } else {
                return "[Zhipu] 调用失败: HTTP " + response.statusCode() + "\n" + response.body();
            }
        } catch (Exception ex) {
            return "[Zhipu] 异常: " + ex.getMessage();
        }
    }

    private String buildPrompt(User user, Consultation c) {
        StringBuilder sb = new StringBuilder();
        sb.append("你是资深汽车顾问。请根据以下用户与咨询信息提供详细建议：\n");
        sb.append("用户基本偏好：预算").append(user.getBudgetMin()).append("-").append(user.getBudgetMax())
                .append(", 车型: ").append(nullToEmpty(user.getPreferredBodyType())).append("\n");
        sb.append("咨询：预算").append(c.getBudgetMin()).append("-").append(c.getBudgetMax())
                .append(", 类型: ").append(nullToEmpty(c.getBodyType()))
                .append(", 场景: ").append(nullToEmpty(c.getScenes()))
                .append(", 能源: ").append(nullToEmpty(c.getFuelType()))
                .append(", 品牌偏好: ").append(nullToEmpty(c.getBrandPreference())).append("\n");
        sb.append("输出结构：推荐车型、对比分析、预算规划、专业知识答疑与购车注意事项。\n");
        return sb.toString();
    }

    private String nullToEmpty(String s) { return s == null ? "" : s; }
    private String demoAdvice(String prompt) {
        return "基于提示：\n" + prompt + "\n- 推荐：轿车/MPV混动方案\n- 对比：舒适性/保值率/充电便利性\n- 预算：建议考虑金融方案\n- 解答：新能源补贴与限购政策";
    }
}